package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.message.ErrorMessage;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient client;

    @Override
    public Result queryShopById(Long id) {
         //解决缓存穿透问题
//        Shop shop = client.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //互斥锁缓存击穿问题
//        Shop shop = client.queryShopIdWithMutex(RedisConstants.CACHE_SHOP_KEY,id, Shop.class,
//                this::getById,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
       //逻辑过期解决缓存击穿问题
        Shop shop = client.queryShopIdWithLogicExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail(ErrorMessage.SHOP_NOT_EXIST);
        }
        return Result.ok(shop);
    }

    /**
     * 利用逻辑过期解决缓存击穿问题
     *
     * @param id
     * @return
     */
//    private Shop queryShopIdWithLogicExpire(Long id) {
//        //1.在缓存中查询商品是否存在
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        //2.未命中返回空
//        if (StringUtils.isEmpty(shopJson)) {
//            //缓存未命中
//            return null;
//        }
//        //3. 命中，需要判断缓存是否过期
//        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
//        //4. 未过期，直接返回商铺信息
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            return shop;
//        }
//        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
//        //5. 过期，尝试获取互斥锁
//        if (tyrLock(lockKey)) {
//            //获取锁成功，应该再查一次redis
//            shopJson = stringRedisTemplate.opsForValue().get(key);
//            if (StringUtils.isEmpty(shopJson)) {
//                unLocak(lockKey);
//                return null;
//            }
//            redisData = JSONUtil.toBean(shopJson, RedisData.class);
//            expireTime = redisData.getExpireTime();
//            shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
//            if (expireTime.isAfter(LocalDateTime.now())) {
//                unLocak(lockKey);
//                return shop;
//            }
//            //又查了一次，还是过期，开启独立线程进行缓存重建
//            CACHE_REBUILD_EXECUTOR.submit(() -> {
//                try {
//                    this.savaShop2Redis(id, 20L);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                } finally {
//                    unLocak(lockKey);
//                }
//            });
//        }
//        return shop;
//    }

    /**
     * 保存店铺信息到redis中，给redis预热用来测试
     *
     * @param id
     * @param expireSeconds
     */
//    public void savaShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
//        Shop shop = getById(id);
//        Thread.sleep(200);
//        RedisData data = new RedisData();
//        data.setData(shop);
//        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(data), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//    }

    /**
     * 利用互斥锁解决缓存击穿问题
     *
     * @param id
     * @return
     */
//    private Shop queryShopIdWithMutex(Long id) {
//        //1.在缓存中查询商品是否存在
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        //2.存在，直接返回
//        if (!StringUtils.isEmpty(shopJson)) {
//            log.info("redis缓存命中直接返回........");
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        //到达这里有两种可能，null || ""
//        if (shopJson != null) {
//            log.info("空值命中...");
//            return null;
//        }
//        log.info("redis缓存未命中，查询数据库。。。。。。。。。。");
//        //尝试获取互斥锁
//        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
//        Shop shop = null;
//        try {
//            if (!tyrLock(lockKey)) {
//                //未获取到互斥锁，休眠一段时间，然后重新获取
//                Thread.sleep(50);
//                return queryShopIdWithMutex(id);
//            }
//            //获取到了互斥锁，再次查询缓存中是否有数据
//            String shopJson2 = stringRedisTemplate.opsForValue().get(key);
//            if (!StringUtils.isEmpty(shopJson2)) {
//                log.info("redis缓存命中直接返回........");
//                return JSONUtil.toBean(shopJson, Shop.class);
//            }
//            if (shopJson2 != null) {
//                log.info("空值命中...");
//                return null;
//            }
//            //缓存中不存在，查询数据库，重建缓存
//            shop = getById(id);
//            //模拟重建
//            Thread.sleep(200);
//            if (shop == null) {
//                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            //存在，将商品信息加入redis缓存，并设置超时时间为30min
//            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            //释放互斥锁
//            unLocak(lockKey);
//        }
//        //6.返回商品信息
//        return shop;
//    }

    /**
     * 利用加入空值缓存解决缓存穿透问题
     *
     * @param id
     * @return
     */
//    private Shop queryShopByIdWithThroughOut(Long id) {
//        //1.在缓存中查询商品是否存在
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String shopJson = stringRedisTemplate.opsForValue().get(key);
//        //2.存在，直接返回
//        if (!StringUtils.isEmpty(shopJson)) {
//            return JSONUtil.toBean(shopJson, Shop.class);
//        }
//        //到达这里有两种可能，null || ""
//        if (shopJson != null) {
//            return null;
//        }
//        //3.不存在，在数据库中查询是否存在
//        Shop shop = getById(id);
//        if (shop == null) {
//            //4.不存在，返回错误信息,并将空值加入redis缓存，解决缓存穿透的问题
//            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//            return null;
//        }
//        //5.存在，将商品信息加入redis缓存，并设置超时时间为30min
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        //6.返回商品信息
//        return shop;
//    }

    /**
     * 增加互斥锁
     * @param key
     * @return
     */
//    private boolean tyrLock(String key) {
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(flag);
//    }

    /**
     * 释放互斥锁
     * @param key
     */
//    private void unLocak(String key) {
//        stringRedisTemplate.delete(key);
//    }

    /**
     * redis预热，用于缓存测试
     * @param id
     * @param expireSeconds
     * @throws InterruptedException
     */
    public void savaShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        Thread.sleep(200);
        RedisData data = new RedisData();
        data.setData(shop);
        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(data), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
    }

    /**
     * 更新商铺信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail(ErrorMessage.SHOP_NOT_EXIST);
        }
        //1.先更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //没有传递x,y，走数据库查询
        if (x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current-1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //从redis中获取5km范围内的typeId类型的商铺
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> list = stringRedisTemplate.opsForGeo() // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        if (list == null){
            return Result.ok(Collections.emptyList());
        }
        //解析数据:商铺id,
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> results = list.getContent();
        if (results.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(results.size());
        Map<Long,Distance> map = new HashMap<>(results.size());
        results.stream().skip(from).forEach(result ->{
            Long shopId = Long.valueOf(result.getContent().getName());
            ids.add(shopId);
            Distance distance = result.getDistance();
            map.put(shopId,distance);
        });

        //查询商铺具体信息
        String idsStr = StrUtil.join(",",ids);
        List<Shop> shopList = query().in("id", ids).last("order by field(id," + idsStr + ")").list();
        for (Shop shop : shopList) {
            shop.setDistance(map.get(shop.getId()).getValue());
        }
        return Result.ok(shopList);
    }
}
